package com.lhl.jwt.security.config;

import com.lhl.jwt.security.filter.JwtAuthenticationFilter;
import com.lhl.jwt.security.handler.JwtAuthenticationFailureHandler;
import io.swagger.annotations.Api;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @className: com.lhl.jwt.security.config.JwtAuthenticationConfigurer
 * @description: Jwt 认证 配置器
 * @author: king
 * @date: 2020-12-21 18:17
 **/
@Api(tags = "JwtAuthenticationConfigurer", produces = "JwtAuthenticationConfigurer")
public class JwtAuthenticationConfigurer <T extends JwtAuthenticationConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T, B> {

    private JwtAuthenticationFilter authFilter;

    public JwtAuthenticationConfigurer() {
        authFilter = new JwtAuthenticationFilter();
    }

    @Override
    public void configure(B builder) throws Exception {
        authFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));

        authFilter = postProcess(authFilter);
        builder.addFilterAfter(authFilter, LogoutFilter.class);
    }

    /**
     * 设置白名单
     * @param urls
     * @return
     */
    public JwtAuthenticationConfigurer<T, B> permissiveRequestUrls(String ... urls){
        authFilter.setPermissiveUrl(urls);
        return this;
    }

    /**
     * 设置认证成功后的操作
     * @param successHandler
     * @return
     */
    public JwtAuthenticationConfigurer<T, B> authenticationSuccessHandler(AuthenticationSuccessHandler successHandler){
        authFilter.setAuthenticationSuccessHandler(successHandler);
        return this;
    }

    public JwtAuthenticationConfigurer<T, B> authenticationFailureHandler(JwtAuthenticationFailureHandler failureHandler){
        authFilter.setAuthenticationFailureHandler(failureHandler);
        return this;
    }
}
